package team.tunan.common;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.io.Serializable;
import java.util.List;


/**
 * 分页响应
 * @author : wex
 * @createTime : 2023/10/27 16:01
 */
public class PageResult<T> extends Result<PageResult.PageList<T>> {
    public PageResult() {
    }

    public static <T> PageResult <T> from(Page<T> page){
        if(page == null) {
            PageResult<T> result = new PageResult<T>();
            result.setCode(200);
            result.setMessage("返回成功");
            result.setSuccess(true);
            result.setData(null);
            return result;
        }
        List<T> data = page.getRecords();
        //当前页索引
        long pageCurrent = page.getCurrent();
        //总条数
        long total = page.getTotal();
        PageResult.PageList<T> pageList = new PageResult.PageList();
        pageList.setPage((int) pageCurrent);
        pageList.setTotalCount((int) total);
        pageList.setData(data);
        PageResult<T> result = new PageResult<T>();
        result.setCode(200);
        result.setMessage("返回成功");
        result.setSuccess(true);
        result.setData(pageList);
        return result;
    }

    public static class PageList<E> implements Serializable {
        protected int page;

        protected int totalCount;

        protected List<E> data;

        public  PageList() {}

        public int getPage() {
            return page;
        }

        public void setPage(int page) {
            this.page = page;
        }

        public int getTotalCount() {
            return totalCount;
        }

        public void setTotalCount(int totalCount) {
            this.totalCount = totalCount;
        }

        public List<E> getData() {
            return data;
        }

        public void setData(List<E> data) {
            this.data = data;
        }

        @Override
        public String toString() {
            return "PageList{" +
                    "page=" + page +
                    ", totalCount=" + totalCount +
                    ", data=" + data +
                    '}';
        }
    }
}
